/**
 * 
 */
package org.arpit.masteringextjs.dao.impl;

import java.util.List;

import org.arpit.masteringextjs.dao.CategoryDAO;
import org.arpit.masteringextjs.dao.DBUtility;
import org.arpit.masteringextjs.domain.Actor;
import org.arpit.masteringextjs.domain.Category;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

/**
 * @author arpit
 *
 */
public class CategoryDAOImpl implements CategoryDAO{

	private static CategoryDAO actorDAO;
	private SessionFactory sessionFactory = DBUtility.getSessionFactory();
	private CategoryDAOImpl () {
		
	}
	
	public static CategoryDAO getInstance() {
		if(actorDAO == null) {
			actorDAO = new CategoryDAOImpl();
		}
		return actorDAO;
	}
	
	@Override
	public List<Category> findAll() {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Category.class);
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		List<Category> actors = crit.list();
		session.getTransaction().commit();
		session.close();
		return actors;
	}

	@Override
	public Category create(Category actor) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Category createdActor = (Category) session.merge(actor);
		session.getTransaction().commit();
		session.close();
		return createdActor;
	}

	@Override
	public Category update(Category category) {
		if(category.getId() == null || category.getId() == 0) {
			throw new IllegalArgumentException("Invalid data");
		}
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Category updatedActor = (Category) session.merge(category);
		session.getTransaction().commit();
		session.close();
		return updatedActor;
	}

	@Override
	public void delete(long id) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Category.class);
		crit.add(Restrictions.eq("id", id));
		List<Category> categories = crit.list();
		if(categories.isEmpty()) {
			throw new IllegalArgumentException("Category with id " + id +" not found");
		}
		Category category = categories.get(0);
		session.delete(category);
		session.getTransaction().commit();
		session.close();
	}

}
